package org.esprit.ocm.client.ui.one;

import java.util.List;

import org.esprit.ocm.client.model.oca.datasource.ClusterLocalDS;
import org.esprit.ocm.client.model.oca.datasource.HostLocalDS;
import org.esprit.ocm.client.rpc.oca.ClusterOcaService;
import org.esprit.ocm.client.rpc.oca.ClusterOcaServiceAsync;
import org.esprit.ocm.client.rpc.oca.HostOcaService;
import org.esprit.ocm.client.rpc.oca.HostOcaServiceAsync;
import org.esprit.ocm.dto.impl.AwsCredentialsDto;
import org.esprit.ocm.dto.impl.ServerDto;
import org.esprit.ocm.dto.impl.UserDto;
import org.esprit.ocm.model.oca.ClusterOca;
import org.esprit.ocm.model.oca.HostOca;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.viewer.DetailViewer;
import com.smartgwt.client.widgets.viewer.DetailViewerField;

public class HostZone extends SectionStack {

	private final HostOcaServiceAsync		hostOcaService		= GWT.create(HostOcaService.class);
	private final ClusterOcaServiceAsync	clusterOcaService	= GWT.create(ClusterOcaService.class);

	private DataSource						ds;
	private DataSource						dsCluster;
	private ListGrid						grid;
	private ListGrid						gridCluster;
	private DetailViewer					details;
	private DetailViewer					detailsTemplate;

	public HostZone(final ServerDto server, final AwsCredentialsDto credentials, final UserDto user) {

		getData(server, credentials);

		// creer imageSection
		SectionStackSection hostSection = new SectionStackSection("Host List");
		hostSection.setExpanded(true);
		addSection(hostSection);

		// creer imageGrid
		grid = new ListGrid();
		setVisibilityMode(VisibilityMode.MULTIPLE);
		setHeaderHeight(20);
		grid.setShowFilterEditor(true);
		grid.setFilterOnKeypress(true);
		grid.setAutoFetchData(true);

		// creer imagetoolstrip
		ToolStrip hostGridToolStrip = new ToolStrip();
		hostGridToolStrip.setWidth100();
		hostGridToolStrip.addFill();

		// ajouter toolstrip a instanceSection
		hostSection.addItem(hostGridToolStrip);

		// creer filterButton
		final Button filterButton = new Button("Filter");
		filterButton.setShowRollOver(true);
		filterButton.setShowDown(true);
		filterButton.setIcon("filter.png");
		filterButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				grid.setShowFilterEditor(true);
				grid.setFilterOnKeypress(true);
				filterButton.addClickHandler(new ClickHandler() {

					public void onClick(ClickEvent event) {
						grid.setShowFilterEditor(false);

					}
				});
			}
		});

		/**
		 * Host Buttons
		 */
		final Button hostButton = new Button("New Host");
		hostButton.setShowRollOver(true);
		hostButton.setShowDown(true);
		hostButton.setIcon("add.png");
		hostButton.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				CreateHost createHost = new CreateHost(server, credentials, user);
				createHost.show();
			}
		});

		final Button deleteHostButton = new Button("Delete host");
		deleteHostButton.setShowRollOver(true);
		deleteHostButton.setShowDown(true);
		deleteHostButton.setIcon("remove.png");
		deleteHostButton.disable();
		deleteHostButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();
				hostOcaService.delete(secret, endpoint, Integer.parseInt(grid.getSelectedRecord().getAttribute("id")), new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub

					}
				});
			}
		});

		final Button enablehostButton = new Button("Enable Host");
		enablehostButton.setShowRollOver(true);
		enablehostButton.setShowDown(true);
		enablehostButton.setIcon("add.png");
		enablehostButton.disable();
		enablehostButton.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				
				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int hostId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				hostOcaService.enable(secret, endpoint, hostId, new AsyncCallback<String>() {
					
					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}
					
					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub
						
					}
				});
			}
		});

		final Button disablehostButton = new Button("Disable Host");
		disablehostButton.setShowRollOver(true);
		disablehostButton.setShowDown(true);
		disablehostButton.setIcon("add.png");
		disablehostButton.disable();
		disablehostButton.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int hostId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				hostOcaService.disable(secret, endpoint, hostId, new AsyncCallback<String>() {
					
					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}
					
					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub
						
					}
				});
			}
		});

		/**
		 * Cluster Buttons
		 */
		final Button clusterButton = new Button("New Cluster");
		clusterButton.setShowRollOver(true);
		clusterButton.setShowDown(true);
		clusterButton.setIcon("add.png");
		clusterButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				CreateCluster createCluster = new CreateCluster(server, credentials, user);
				createCluster.show();
			}
		});

		final Button deleteClusterButton = new Button("Delete cluster");
		deleteClusterButton.setShowRollOver(true);
		deleteClusterButton.setShowDown(true);
		deleteClusterButton.disable();
		deleteClusterButton.setIcon("remove.png");
		deleteClusterButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int clusterId = Integer.parseInt(gridCluster.getSelectedRecord().getAttribute("id"));

				clusterOcaService.delete(secret, endpoint, clusterId, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						dsCluster.destroy();
						getData(server, credentials);
						grid.redraw();
						gridCluster.redraw();
					}

					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub

					}
				});

			}
		});

		final Button addH2CButton = new Button("Host->Cluster");
		addH2CButton.setShowRollOver(true);
		addH2CButton.setShowDown(true);
		addH2CButton.setIcon("add.png");
		addH2CButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int clusterId = Integer.parseInt(gridCluster.getSelectedRecord().getAttribute("id"));
				int hostId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				clusterOcaService.addHost(secret, endpoint, clusterId, hostId, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub

					}
				});
			}
		});

		final Button removeHfCButton = new Button("Host -x- Cluster");
		removeHfCButton.setShowRollOver(true);
		removeHfCButton.setShowDown(true);
		removeHfCButton.disable();
		removeHfCButton.setIcon("add.png");
		removeHfCButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				
				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int hostId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				clusterOcaService.removeHost(secret, endpoint, hostId, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub

					}
				});
			}
		});

		/**
		 * Refresh
		 */
		final Button refreshButton = new Button("Refresh");
		refreshButton.setShowRollOver(true);
		refreshButton.setShowDown(true);
		refreshButton.setIcon("interact.png");
		refreshButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				SC.say("Refreshed");
				ds.destroy();
				dsCluster.destroy();
				getData(server, credentials);
				grid.redraw();
				gridCluster.redraw();
			}
		});
		
		Img filter = new Img("filter.png", 15, 15);

		// creer filterButton
		final Button filterButtonOn = new Button("On");
		filterButtonOn.setWidth(25);
		filterButtonOn.setHeight(20);
		filterButtonOn.setShowRollOver(true);
		filterButtonOn.setShowDown(true);
		// filterButtonOn.setIcon("filter.png");
		filterButtonOn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				grid.setShowFilterEditor(true);
				grid.setFilterOnKeypress(true);
			}
		});
		// creer filterButton
		final Button filterButtonOff = new Button("Off");
		filterButtonOff.setWidth(25);
		filterButtonOff.setHeight(20);
		filterButtonOff.setShowRollOver(true);
		filterButtonOff.setShowDown(true);
		// filterButtonOff.setIcon("filter.png");
		filterButtonOff.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				grid.setShowFilterEditor(false);
				grid.setFilterOnKeypress(false);
			}
		});

		// ajouter le bouton
		hostGridToolStrip.addMember(hostButton);
		hostGridToolStrip.addMember(deleteHostButton);
		hostGridToolStrip.addSpacer(30);
		hostGridToolStrip.addMember(enablehostButton);
		hostGridToolStrip.addMember(disablehostButton);
		hostGridToolStrip.addSpacer(30);
		hostGridToolStrip.addMember(clusterButton);
		hostGridToolStrip.addMember(deleteClusterButton);
		hostGridToolStrip.addSpacer(30);
		hostGridToolStrip.addMember(addH2CButton);
		hostGridToolStrip.addMember(removeHfCButton);
		hostGridToolStrip.addSpacer(30);
		hostGridToolStrip.addMember(refreshButton);
		hostGridToolStrip.addSpacer(10);
		hostGridToolStrip.addMember(filter);
		hostGridToolStrip.addSpacer(2);
		hostGridToolStrip.addMember(filterButtonOn);
		hostGridToolStrip.addMember(filterButtonOff);
		hostGridToolStrip.addSpacer(5);

		// ajouter instanceGrid a instanceSection
		hostSection.addItem(grid);

		// creer DetailinstanceSection

		details = new DetailViewer();
		details.setWidth100();
		details.setMargin(15);
		details.setEmptyMessage("Select something to view its details");

		detailsTemplate = new DetailViewer();
		detailsTemplate.setWidth100();
		detailsTemplate.setMargin(15);
		detailsTemplate.setEmptyMessage("Select something to view its details");

		grid.addRecordClickHandler(new RecordClickHandler() {

			public void onRecordClick(RecordClickEvent event) {

				details.setData(new Record[] { event.getRecord() });
				detailsTemplate.setData(new Record[] { event.getRecord() });

				deleteClusterButton.disable();

				deleteHostButton.enable();
				enablehostButton.enable();
				disablehostButton.enable();

				removeHfCButton.enable();

			}
		});

		HLayout viewDetail = new HLayout();
		viewDetail.setHeight("30%");
		viewDetail.setPadding(5);

		viewDetail.addMember(details);
		viewDetail.addMember(detailsTemplate);

		// creer imageSection
		SectionStackSection clusterSection = new SectionStackSection("Cluster List");
		clusterSection.setExpanded(true);
		addSection(clusterSection);

		// creer imageGrid
		gridCluster = new ListGrid();
		setVisibilityMode(VisibilityMode.MULTIPLE);
		setHeaderHeight(20);
		gridCluster.setShowFilterEditor(true);
		gridCluster.setFilterOnKeypress(true);
		gridCluster.setAutoFetchData(true);

		gridCluster.addRecordClickHandler(new RecordClickHandler() {

			public void onRecordClick(RecordClickEvent event) {

				deleteClusterButton.enable();

				deleteHostButton.disable();
				enablehostButton.disable();
				disablehostButton.disable();

				removeHfCButton.disable();
			}
		});

		clusterSection.addItem(gridCluster);

		SectionStackSection hostDetailSection = new SectionStackSection("Host Detail");
		hostDetailSection.setExpanded(true);
		hostDetailSection.addItem(viewDetail);
		addSection(hostDetailSection);

		// draw();
	}

	private void getData(ServerDto server, AwsCredentialsDto credentials) {

		String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
		String endpoint = server.getIpServer();

		clusterOcaService.listAll(secret, endpoint, new AsyncCallback<List<ClusterOca>>() {

			public void onSuccess(List<ClusterOca> list) {
				// TODO Auto-generated method stub
				for (ClusterOca clusterOca : list) {
					System.out.println(clusterOca.getId());
				}

				dsCluster = new DataSource();
				dsCluster = ClusterLocalDS.getInstance(list);

				gridCluster.setDataSource(dsCluster);

				ListGridField idClusterField = new ListGridField("id", "id");
				ListGridField nameClusterField = new ListGridField("name", "name");

				gridCluster.setFields(idClusterField, nameClusterField);

			}

			public void onFailure(Throwable arg0) {
				// TODO Auto-generated method stub

			}
		});

		hostOcaService.listAll(secret, endpoint, new AsyncCallback<List<HostOca>>() {

			public void onSuccess(List<HostOca> list) {
				// TODO Auto-generated method stub
				for (HostOca hostOca : list) {
					System.out.println(hostOca.getId());
				}

				ds = new DataSource();
				ds = HostLocalDS.getInstance(list);

				grid.setDataSource(ds);
				details.setDataSource(ds);
				detailsTemplate.setDataSource(ds);

				ListGridField idField = new ListGridField("id");
				ListGridField name = new ListGridField("name");
				ListGridField state = new ListGridField("state");
				ListGridField im_mad = new ListGridField("im_mad");
				ListGridField vm_mad = new ListGridField("vm_mad");
				ListGridField tm_mad = new ListGridField("tm_mad");
				ListGridField last_mon_time = new ListGridField("last_mon_time");
				ListGridField cluster = new ListGridField("cluster");

				grid.setFields(idField, name, state, im_mad, vm_mad, tm_mad, last_mon_time, cluster);

				DetailViewerField template_cpuspeed = new DetailViewerField("template_cpuspeed", "template_cpuspeed");
				DetailViewerField template_freecpu = new DetailViewerField("template_freecpu", "template_freecpu");
				DetailViewerField template_freememory = new DetailViewerField("template_freememory", "template_freememory");
				DetailViewerField template_hostname = new DetailViewerField("template_hostname", "template_hostname");
				DetailViewerField template_hypervisor = new DetailViewerField("template_hypervisor", "template_hypervisor");
				DetailViewerField template_name = new DetailViewerField("template_name", "template_name");
				DetailViewerField template_totalcpu = new DetailViewerField("template_totalcpu", "template_totalcpu");
				DetailViewerField template_totalmemory = new DetailViewerField("template_totalmemory", "template_totalmemory");
				DetailViewerField template_usedcpu = new DetailViewerField("template_usedcpu", "template_usedcpu");
				DetailViewerField template_usedmemory = new DetailViewerField("template_usedmemory", "template_usedmemory");

				detailsTemplate.setFields(template_cpuspeed, template_freecpu, template_freememory, template_hostname, template_hypervisor,
						template_name, template_totalcpu, template_totalmemory, template_usedcpu, template_usedmemory);

				DetailViewerField host_share_hid = new DetailViewerField("host_share_hid", "host_share_hid");
				DetailViewerField host_share_disk_usage = new DetailViewerField("host_share_disk_usage", "host_share_disk_usage");
				DetailViewerField host_share_mem_usage = new DetailViewerField("host_share_mem_usage", "host_share_mem_usage");
				DetailViewerField host_share_cpu_usage = new DetailViewerField("host_share_cpu_usage", "host_share_cpu_usage");
				DetailViewerField host_share_max_disk = new DetailViewerField("host_share_max_disk", "host_share_max_disk");
				DetailViewerField host_share_max_mem = new DetailViewerField("host_share_max_mem", "host_share_max_mem");
				DetailViewerField host_share_max_cpu = new DetailViewerField("host_share_max_cpu", "host_share_max_cpu");
				DetailViewerField host_share_free_disk = new DetailViewerField("host_share_free_disk", "host_share_free_disk");
				DetailViewerField host_share_free_mem = new DetailViewerField("host_share_free_mem", "host_share_free_mem");
				DetailViewerField host_share_free_cpu = new DetailViewerField("host_share_free_cpu", "host_share_free_cpu");
				DetailViewerField host_share_used_disk = new DetailViewerField("host_share_used_disk", "host_share_used_disk");
				DetailViewerField host_share_used_mem = new DetailViewerField("host_share_used_mem", "host_share_used_mem");
				DetailViewerField host_share_used_cpu = new DetailViewerField("host_share_used_cpu", "host_share_used_cpu");
				DetailViewerField host_share_running_vms = new DetailViewerField("host_share_running_vms", "host_share_running_vms");

				details.setFields(host_share_hid, host_share_disk_usage, host_share_mem_usage, host_share_cpu_usage, host_share_max_disk,
						host_share_max_mem, host_share_max_cpu, host_share_free_disk, host_share_free_mem, host_share_free_cpu, host_share_used_disk,
						host_share_used_mem, host_share_used_cpu, host_share_running_vms);

			}

			public void onFailure(Throwable arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

}
